package com.central.apps.handler.contract;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ContemplateHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_contemplate".equals(objName) && !isUpdate) {
            String tename = MapUtils.getString(data, "tename");
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_contemplate where tename = '" + tename + "' and delflag =0");
            if (CollectionUtils.isNotEmpty(list)) {
                throw new ServiceException("模板已存在，请修改模板名称在保存");
            }
        }
    }
    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        if("submit".equals(flowNode.getId())){
            List<Map<String, Object>> list = handlerService.findBySql("select fileid from tb_file where appname = '" + app + "' and recordid = "+id);
            if (CollectionUtils.isEmpty(list)) {
                return "请上传合同模板文件再提交审批";
            }

            //体检前，验收一下合同类型是否被删除
            List<Map<String,Object>> list2 = handlerService.findBySql(" select id from gq_contracttype where id in (select typeid from gq_contemplate where id="+id+")");
            if(CollectionUtils.isEmpty(list2)){
                return "合同类型数据已删除，请重新选择合同类型";
            }
        }

        //审批通过后，将合同模板编号同步到合同类型里边
//        if("approval".equals(flowNode.getId())&&op.isFlag()){
//            List<Map<String,Object>> list2 = handlerService.findBySql("select tecode,typeid,isframecon from gq_contemplate where id = "+id);
//            String tecode = MapUtils.getString(list2.get(0),"tecode");//模板编号
//            int typeid = MapUtils.getInteger(list2.get(0),"typeid");//类型主键id
//            String isframecon = MapUtils.getString(list2.get(0),"isframecon");//是否是框架合同
//            String upd = "update gq_contracttype set tecode = '"+tecode+"',isframecon = '"+isframecon+"'  where id = '"+typeid+"'";
//            handlerService.updateBySql(upd);
//        }


        return super.beforeExcuteFlow(app, id, flowNode, op);
    }
}
